from datetime import datetime
from app import db
from flask_login import current_user


class Log(db.Model):
    """系统日志模型"""
    __tablename__ = 'logs'
    
    id = db.Column(db.Integer, primary_key=True)
    level = db.Column(db.String(20), nullable=False, default='INFO')  # 日志级别: INFO, WARNING, ERROR, CRITICAL
    message = db.Column(db.Text, nullable=False)  # 日志消息
    details = db.Column(db.Text)  # 详细信息
    ip_address = db.Column(db.String(45))  # IP地址
    user_agent = db.Column(db.String(255))  # 用户代理
    url = db.Column(db.String(255))  # 请求URL
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True)  # 关联用户
    created_at = db.Column(db.DateTime, default=datetime.utcnow)  # 创建时间
    
    # 关联用户
    user = db.relationship('User', backref=db.backref('logs', lazy='dynamic'))
    
    def __repr__(self):
        return f'<Log {self.id}: {self.level}>'
    
    @staticmethod
    def log(level, message, details=None, ip_address=None, user_agent=None, url=None, user_id=None):
        """记录日志"""
        if user_id is None and current_user.is_authenticated:
            user_id = current_user.id
            
        log = Log(
            level=level,
            message=message,
            details=details,
            ip_address=ip_address,
            user_agent=user_agent,
            url=url,
            user_id=user_id
        )
        db.session.add(log)
        db.session.commit()
        return log
    
    @staticmethod
    def info(message, details=None, ip_address=None, user_agent=None, url=None, user_id=None):
        """记录信息级别日志"""
        return Log.log('INFO', message, details, ip_address, user_agent, url, user_id)
    
    @staticmethod
    def warning(message, details=None, ip_address=None, user_agent=None, url=None, user_id=None):
        """记录警告级别日志"""
        return Log.log('WARNING', message, details, ip_address, user_agent, url, user_id)
    
    @staticmethod
    def error(message, details=None, ip_address=None, user_agent=None, url=None, user_id=None):
        """记录错误级别日志"""
        return Log.log('ERROR', message, details, ip_address, user_agent, url, user_id)
    
    @staticmethod
    def critical(message, details=None, ip_address=None, user_agent=None, url=None, user_id=None):
        """记录严重级别日志"""
        return Log.log('CRITICAL', message, details, ip_address, user_agent, url, user_id)
    
    @staticmethod
    def get_logs(level=None, user_id=None, start_date=None, end_date=None, page=1, per_page=20):
        """获取日志列表"""
        query = Log.query
        
        if level:
            query = query.filter(Log.level == level)
            
        if user_id:
            query = query.filter(Log.user_id == user_id)
            
        if start_date:
            query = query.filter(Log.created_at >= start_date)
            
        if end_date:
            query = query.filter(Log.created_at <= end_date)
            
        # 按创建时间倒序
        query = query.order_by(Log.created_at.desc())
        
        # 分页
        return query.paginate(page=page, per_page=per_page, error_out=False)
    
    @staticmethod
    def clear_all_logs():
        """清空所有日志"""
        Log.query.delete()
        db.session.commit()